#include "Chapter1.h"

int read_column_number(int iCol[], int iMax)
{
	int iNum;
	int iCn;
	iCn = 0;
	iNum = 0;
	
	// read col num
	while(iNum < iMax && scanf("%d",&iCol[iNum]) ==1 && iCol[iNum] >=0)
	{
		iNum++;
	}

	// check if the numbers are in pairs
	if( iNum%2 != 0)
	{
		puts("Err: last column number is not paired!");
		exit(EXIT_FAILURE);
	}

	while( (iCn = getchar()) != EOF && iCn != '\n')
	{}

	return iNum;
}



void rearrange(char *output, char const * input, int iNCol, int const iColumn[])
{
	int iLen, iCol, iNumChar;
	int output_col; 

	iLen = strlen(input);
	output_col = 0;

	for(iCol = 0 ; iCol < iNCol; iCol+=2)
	{
		iNumChar = iColumn[iCol+1] - iColumn[iCol] + 1;

		if( iColumn[iCol] > iLen || output_col == MAX_INPUT - 1)
			break;

		if( output_col + iNumChar > MAX_INPUT -1)
			iNumChar = MAX_INPUT - output_col - 1;
		
		strncpy(output + output_col, input+iColumn[iCol], iNumChar);
		output_col += iNumChar;
	}
	output[output_col] = '\0';

}


void test_1()
{
	int iCol;  
	int iColumn[MAX_COL];
	char input[MAX_INPUT];
	char output[MAX_INPUT];

	iCol = read_column_number(iColumn,MAX_COL);

	while( gets(input) != NULL)
	{
		printf(" Original input: %s \n", input);
		rearrange(output, input, iCol, iColumn);
		printf(" Rearranged output: %s \n", output);
		
	}
}


void test_1_2()
{
	int iCh;
	int iLine;
	int at_beginning;

	at_beginning = 1;
	iLine =0;

	while( (iCh=getchar())!=EOF)
	{
		if(at_beginning == 1)
		{
			printf("%d", iLine);
			at_beginning =0;
			iLine++;
		}

		putchar(iCh);
		if( iCh =='\n')
			at_beginning = 1;
	}
}